<?php
namespace Admin\Controller;
use \Think\Controller;
//此控制器处理登陆相关
class LoginController extends Controller{
    //执行登陆
    
     public function index()
    {
        $this->display('Login/index');
    }

    public function vcode()
    {
        $Verify = new \Think\Verify();
        $Verify->length = 4;
        $Verify->entry();
    }



    public function login()
    {
        foreach ($_POST as $val) {
            if (empty($val)) {
                $this->error('请完善数据',U('Login/index'),1);
                exit;
            }
        }
        $vcode = I('post.vcode');
        if (!check_verify($vcode)) {
            $this->error('验证码错误',U('Login/index'),1);
            exit;
        }
        // 用户密码验证
        $password = md5(I('post.pass'));
        //拿到POST里面的用户名和密码
        $data['username'] = I('post.name');
        $user = D('admin');
        //用用户名进数据库进行查询
        $u = $user->where($data)->find();
        if (!$u) {
            $this->error('用户名不存在',U('Login/index'),1);
        } elseif ($password != $u['pass']) {
            $this->error('密码错误',U('Login/index'),1);
        } elseif ($u['denied'] == 0) {
            $this->error('您的账号已被禁用',U('Login/index'));
        } else {

            if ($u['username'] != 'admin') {

            
            //查询角色
            $roles = M('user_role')->field('rid')->where('uid='.$u['id'])->select();
            //取出数组下标
            $arr = array();
            foreach ($roles as $val) {
                $arr[] = $val[rid];
            }
            $roles = $arr;
            //查询角色对应的权限
            $r = M('role_node');
            $nodes = array();
            foreach ($roles as $val) {

            $nodes[] = $r->field('nid')->where('rid='.$val)->select();
            }
            // 对结果变形
            $arr = array();
            foreach ($nodes as $val) {
                foreach ($val as $v) {
                    $arr[] = $v['nid'];
                }
            }
            $nodes = array_unique($arr);
            // var_dump($nodes);
            // 拿到权限后,查询权限对应的aname;
            $map['id'] = array('in',$nodes);
            $nodes = M('node')->field('aname')->where($map)->select();
            //重组aname
            $arr = array();
            foreach ($nodes as $val) {
                $arr[] = $val[aname];
            }
            $nodes = $arr;
        }  //if结束

            //正确,写入session
            $admin_user['nodelist'] = $nodes;
            $admin_user['id'] = $u['id'];
            $admin_user['name'] = $u['name'];
            $admin_user['username'] = $u['username'];
            $admin_user['image'] = $u['image'];
            session('verify_code', null);
            session('verify_time', null);
            session('admin_user',$admin_user);
           
            $this->redirect('Index/index');
        }  //else结束
    }

    public function logout()
    {
        session('admin_user', null);
        $this->redirect('Login/index');
    }
}